package com.system.controller;

import com.system.pojo.Result;
import com.system.pojo.administrator;
import com.system.pojo.ownerinfo;
import com.system.service.UserService;
import com.system.utils.JwtUtil;
import com.system.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result userRegister(String name,String password){
        ownerinfo a =userService.findByUserName(name);
        if(a==null){
            userService.register(name,password);
            return Result.success();
        }else{
            return Result.error("用户名已被占用");
        }
    }

    @PostMapping("/login")
    public Result<String> userLogin(String name,String password){
        ownerinfo loginUser = userService.findByUserName(name);
        if(loginUser==null){
            return Result.error("账号错误");
        }
        if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",loginUser.getOwnerID());
            claims.put("name",loginUser.getName());
            String token = JwtUtil.genToken(claims);

            return Result.success(token);
        }
        return Result.error("密码错误");
    }

}
